using System;
using System.Collections.Generic;
using PowerSearch.Core;
using System.Xml.Linq;
using System.Linq;

namespace PowerSearch.AppServices.Parser.Provider
{
	public class BBCParser : BaseFeedParser
	{
		private const string FeedUrl = "http://feeds.bbci.co.uk/news/rss.xml";

		public override string BaseUrl
		{
			get
			{

				return FeedUrl;
			}
		}

		#region Overridden methods

		protected internal override IList<Feed> ParseFeed(string data)
		{
			var feedList = new List<Feed>();
			var xmlDoc = XDocument.Parse(data);
			if (xmlDoc.Root != null)
			{
				var xmlns = xmlDoc.Root.GetDefaultNamespace();
				var xmlnsMedia = xmlDoc.Root.GetNamespaceOfPrefix("media");
				xmlDoc.Root.Descendants(xmlns + "item").ToList().ForEach(element => feedList.Add(CreateFeedItem(element, xmlnsMedia, xmlns)));
			}
			return feedList;
		}

		#endregion

		#region Private methods
		private Feed CreateFeedItem(XElement xElement, XNamespace xmlnsMedia, XNamespace xmlns)
		{

			var title = xElement.Element(xmlns + "title") != null ? xElement.Element(xmlns + "title").Value : string.Empty;
			var description = xElement.Element(xmlns + "description") != null ? xElement.Element(xmlns + "description").Value : string.Empty;
			var clickUrl = xElement.Element(xmlns + "link") != null ? xElement.Element(xmlns + "link").Value : string.Empty;
			var thumbnail = xElement.Element(xmlnsMedia + "thumbnail") != null ? xElement.Element(xmlnsMedia + "thumbnail").Attribute("url") : null;
			var displayUrl = thumbnail != null ? thumbnail.Value : string.Empty;

			var feed = new Feed
			{
				Title = title,
				Description = description,
				ClickUrl = clickUrl,
				DisplayUrl = displayUrl
			};
			return feed;
		}
		#endregion
	}
}

